package com.thinvent.nj.ais.controller.sys;

import com.alibaba.fastjson.JSONObject;
import com.thinvent.nj.common.rest.ResponseEntity;
import com.thinvent.nj.common.util.CollectionUtil;
import com.thinvent.nj.common.util.MapperUtil;
import com.thinvent.nj.common.util.StringUtil;
import com.thinvent.nj.ais.entity.Resource;
import com.thinvent.nj.ais.entity.Role;
import com.thinvent.nj.ais.entity.User;
import com.thinvent.nj.ais.service.RoleService;
import com.thinvent.nj.ais.service.UserService;
import com.thinvent.nj.web.controller.BaseViewController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 角色管理controller
 * @author liupeijun
 */
@Controller
@RequestMapping(path = "/sys/roles")
public class RoleController extends BaseViewController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserService userService;

    @RequiresPermissions("role:view")
    @RequestMapping(method = RequestMethod.GET)
    public String toHtml() {
        return "sys/roleList";
    }

    @RequiresPermissions("role:view")
    @RequestMapping(path = "/search/page", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity findTableData(@RequestBody Map<String, Object> params) {
        List<Role> targets = roleService.findListByOrgId(getQueryMsgString(params, "orgId"));

        JSONObject jsonObject = new JSONObject(1);
        jsonObject.put("result", targets);

        return ResponseEntity.ok(jsonObject);
    }

    @RequiresPermissions("role:view")
    @RequestMapping(path = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity get(@PathVariable("id") String id) {
        Role target = roleService.get(id);
        List<User> users = userService.findByRoleId(id);

        target.setUserList(users);

        return ResponseEntity.ok(target);
    }

    @RequiresPermissions("role:add")
    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity insert(@RequestBody Map<String, Object> params) {
      Role target = new Role();
      MapperUtil.copy(params, target);

      roleService.insert(target);

        return ResponseEntity.ok();
    }

    @RequiresPermissions("role:update")
    @RequestMapping(path = "/{id}", method = RequestMethod.PUT)
    @ResponseBody
    public ResponseEntity update(@PathVariable("id") String id, @RequestBody Map<String, Object> params) {
        Role target = roleService.get(id);
        MapperUtil.copy(params, target);

        roleService.update(target);

        return ResponseEntity.ok();
    }

    @RequiresPermissions("role:update")
    @RequestMapping(path = "/{id}/resources", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity saveRoleResources(@PathVariable("id") String id, @RequestBody Map<String, Object> params) {
        // 关联资源列表
        String[] resourceIds = ((String)params.get("resourceList")).split(",");
        List<Resource> resources = new ArrayList<>(resourceIds.length);
        for(String resourceId: resourceIds) {
            if (!StringUtil.isNullOrEmpty(resourceId)) {
                resources.add(new Resource(resourceId));
            }

        }

        roleService.saveRoleResources(id, resources);

        return ResponseEntity.ok();
    }

    @RequiresPermissions("role:update")
    @RequestMapping(path = "/{id}/users", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity saveRoleUsers(@PathVariable("id") String id, @RequestBody Map<String, Object> params) {
        // 关联用户列表
        String[] userIds = ((String)params.get("userList")).split(",");
        List<User> users = new ArrayList<>(userIds.length);
        for(String userId: userIds) {
            if (!StringUtil.isNullOrEmpty(userId)) {
                users.add(new User(userId));
            }
        }

        roleService.saveRoleUsers(id, users);
        return ResponseEntity.ok();
    }

    @RequiresPermissions("role:delete")
    @RequestMapping(path = "/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public ResponseEntity del(@PathVariable("id") String id) {
        roleService.delete(id);
        return ResponseEntity.ok();
    }

    @RequestMapping(path = "/tree", method = RequestMethod.POST)
    public void tree() {
        List<Role> targets = roleService.findListByOrgId("CDC53286176D481884ABCF1B7B0945A9");

        render(CollectionUtil.listToZtree(MapperUtil.convertToListMap(targets), "id", "pId", "name"));
    }
}
